<?php
namespace Api\Controller;
use Api\Common\Page;
use Think\Model;
use Common\Model\BookModel;

class BookController extends BaseController {

    //读取所有数据
    public function all() {
        $map['is_del'] = 0;
        $m = M('Book');
        $count = $m->where($map)->count();// 查询满足要求的总记录数
        $Page = new  Page($count ,100);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $data = $m->where($map)
            ->field($this->get_export_field())
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->order('book_id desc')
            ->select();
        foreach ($data as $k => $v){
            $r = M("order_has_book")->where(array(["book_id"=>$v["book_id"],["type"=>1],["is_backed"=>0]]))
                ->field("sum(quantity) as quantity,sum(num_backed) as num_backed,sum(num_broken) as num_broken")
                ->group("book_id")
                ->find();
            $data[$k]["num_loan"] = $r['quantity']-$r['num_backed']-$r['num_broken'];
            unset($data[$k]["book_id"]);
        }
        echo json_encode($data);
    }

    //读取接口数据
    public function getAll(){

        //获取所有数据，用分页搜索
        $i = 1;
        $all = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//如果成功只将结果返回，不自动输出任何内容。如果失败返回FALSE
        do{
            curl_setopt($ch, CURLOPT_URL, "http://xsc.sunday.so/api/Book/all?p=".$i);
            $data = curl_exec($ch);
            $data = json_decode($data,true);
            if(!empty($data)){
                $all[] = $data;
            }
            $i++;
        }while(!empty($data));
        curl_close($ch);
        var_dump($all);

        exit;



//        //获取一条数据，用book_id搜索
//        //1.初始化，创建一个新cURL资源
//        $ch = curl_init();
//
//        //2.设置URL和相应的选项
//        curl_setopt($ch, CURLOPT_URL, "http://xsc.sunday.so/api/Book/one?spbs=0843621");
//        curl_setopt($ch, CURLOPT_HEADER, 0);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//如果成功只将结果返回，不自动输出任何内容。如果失败返回FALSE
//
//        //3.抓取URL并把它传递给浏览器
//        $a = curl_exec($ch);
//        echo $a;
//
//        //4.关闭cURL资源，并且释放系统资源
//        curl_close($ch);

    }

    //只读取一条数据
    public function one() {
        $map['is_del'] = 0;
        if (!empty(I('get.spbs',""))) {
            $map['spbs'] = I('get.spbs',"");
            $m = M('Book');
            $data = $m->where($map)
                ->field($this->get_export_field())
                ->order('book_id desc')->select();
            foreach ($data as $k => $v){
                $r = M("order_has_book")->where(array(["book_id"=>$v["book_id"],["type"=>1],["is_backed"=>0]]))
                    ->field("sum(quantity) as quantity,sum(num_backed) as num_backed,sum(num_broken) as num_broken")
                    ->group("book_id")
                    ->find();
                $data[$k]["num_loan"] = $r['quantity']-$r['num_backed']-$r['num_broken'];
                unset($data[$k]["book_id"]);
            }
        }else{
            $data = "请指定spbs！";
        }
        $this->ajaxReturn($data);
    }
    //读取接口数据
    public function getOne(){

//        //获取所有数据，用分页搜索
//        $i = 1;
//        $all = array();
//        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_HEADER, 0);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//如果成功只将结果返回，不自动输出任何内容。如果失败返回FALSE
//        do{
//            curl_setopt($ch, CURLOPT_URL, "http://xsc.sunday.so/api/Book/all?p=".$i);
//            $data = curl_exec($ch);
//            $data = json_decode($data,true);
//            if(!empty($data)){
//                $all[] = $data;
//            }
//            $i++;
//        }while(!empty($data));
//        curl_close($ch);
//        var_dump($all);
//
//exit;



        //获取一条数据，用book_id搜索
        //1.初始化，创建一个新cURL资源
        $ch = curl_init();

        //2.设置URL和相应的选项
        curl_setopt($ch, CURLOPT_URL, "http://xsc.sunday.so/api/Book/one?spbs=0843621");
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//如果成功只将结果返回，不自动输出任何内容。如果失败返回FALSE

        //3.抓取URL并把它传递给浏览器
        $a = curl_exec($ch);
        echo $a;

        //4.关闭cURL资源，并且释放系统资源
        curl_close($ch);

    }

    //设置返回字段
    function get_export_field(){
        return 'book_id,spbs,stock_rent,stock_buy';
    }

    public function record()
    {
        $card_id = I('card_id');
        if (!$card_id) {
            echo json_encode(['code'=>0,'msg'=>'卡号不能为空'],JSON_UNESCAPED_UNICODE);
            return;
        }
        $page = I('page',1);
        $user = M('card')->where("card_id={$card_id}")->find();
        if (!$user) {
            $this->ajaxReturn(['code'=>404,'msg'=>'card not find']);
        }
        $user_id = $user['user_id'];
        /**
         * order_id -> 订单号
         * tm -> 条码
         * sm -> 书名
         * dj -> 定价
         * quantity -> 借阅数量
         * spbs -> 新华码
         * create_time -> 借阅时间
         * num_backed -> 归还数量
         * num_broken -> 破损数量
         * order_remark -> 订单备注
         */
        $map['user_id'] = $user_id;
        $map['type'] = 1;
        $fields = ['order_id','tm','sm','dj','quantity','spbs','create_time','num_backed','num_broken','state_order','order_remark'];
        $d=M("View_order_has_book")->where($map)->field($fields)->page("{$page},20")->select();
        $d = array_map(function ($item) use ($user){
            $item['child_name'] = $user['child_name'];
            return $item;
        },$d);
        echo json_encode(['code'=>0,'msg'=>$d],JSON_UNESCAPED_UNICODE);
    }

    /**
     * 传入参数
     * @param name 用户名
     * @param daterange 时间范围，中间用 ~ 分割
     * 返回说明
     * borrow_count  -> 借出的数量
     * borrow_total  -> 总借出码洋
     * back_count -> 还入数量
     * back_total -> 还入码洋
     */
    public function adminStats()
    {
        $account = I('name');
        if (!$account) {
            echo json_encode(['code'=>0,'msg'=>'账户名不能为空'],JSON_UNESCAPED_UNICODE);
            return;
        }
        $daterange = I('daterange');
        if ($daterange) {
            list($start,$end) = explode('~', $daterange);
            if (!$end) {
                $this->ajaxReturn(['code' => 400, 'msg' => '日期格式错误']);
            }
        }
        $user = M('admin_user')->where(['account' => $account])->find();
        if (!$user) {
            $this->ajaxReturn(['code'=>404,'msg'=>'user not found']);
        }
        $admin_id = $user['user_id'];
        if (!$admin_id) {
            $this->ajaxReturn(['code' => 404, 'msg' => 'user not found']);
        }
        $query = "select COALESCE(sum(quantity),0) as borrow_count, COALESCE(sum(quantity*dj),0) as borrow_total 
                       from view_record_stats where type = 1 and admin_id = {$admin_id} and mold=0";

        $query1 = "select COALESCE(sum(quantity),0) as back_count, COALESCE(sum(quantity*dj),0) as back_total
                       from view_record_stats where type = 1 and admin_id = {$admin_id} and mold=1";
        if (isset($start) && isset($end)) {
            $start = date('Y-m-d H:i:s',strtotime($start));
            $end = date('Y-m-d H:i:s', strtotime($end));
            $query .= " and create_time between '{$start}' and '{$end}' ";
            $query1 .= " and create_time between '{$start}' and '{$end}' ";
        }
        $d=M()->query($query);
        $d1 = M()->query($query1);
        $result = array_merge($d[0], $d1[0]);
        echo json_encode(['code' => 0, 'msg' => $result]);
    }

    /**
     * 传入参数
     * @param name 用户名
     * @param daterange 时间范围，中间用 ~ 分割
     *
     * [
     *     工号 -> account
     *     时间 -> create_time
     *     借 -> quantity
     *     还 -> num_backed
     *     spbs -> spbs
     *     定价 -> dj
     *     hykh ->  card_id
     * ]
     */
    public function adminStatsList()
    {
        $account = I('name');
        $daterange = I('daterange');
        $page = I('page',1);
        $per_page = I('per_page',15);
        if ($daterange) {
            $daterangeArr = explode('~', $daterange);
            if (count($daterangeArr) !== 2) {
                $this->ajaxReturn(['code' => 403, 'msg' => '日期格式错误']);
            }
        }
        if ($account) {
            $user = M('admin_user')->where(['account' => $account])->find();
            if (!$user) {
                $this->ajaxReturn(['code'=>404,'msg'=>'user not found']);
            }
            $map['admin_id'] = $user['user_id'];
        }
        $model = M('view_record_stats');
        $map['type'] = 1; // 借书
        if (isset($daterangeArr)) {
            $map['create_time'] = array('between', $daterangeArr);
        }

        $result = $model->field("quantity, dj, spbs, num_backed, create_time, account, card_id,mold")
            ->where($map)->page("{$page},{$per_page}")->order('create_time desc')->select();

        echo json_encode(['code' => 0, 'msg' => $result]);
    }

    public function van()
    {
        $admin_order = M('admin_order');
        $data = $admin_order->order('id desc')->where(['type' => 0])->limit(2000)->select();
        foreach ($data as $item) {
            $books = M('order_has_book')->where(['order_id' => $item['order_id']])->select();
            foreach ($books as $book) {
                if (!$admin_order->where(['order_id' => $item['order_id'], 'book_id' => $book['book_id']])->find()) {
                    $admin_order->data(['order_id' => $item['order_id'], 'book_id' => $book['book_id'],
                        'admin_id' => $item['admin_id'], 'type' => 0, 'create_time' => $item['create_time']])->add();
                }
            }
        }
        echo 1;
    }

}